package com.zkingsoft.plugin.util;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

public class HttpUtils {
	/**
     * 向指定URL发送GET方法的请求
     * 
     * @param url
     *            发送请求的URL
     * @param param
     *            请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @return URL 所代表远程资源的响应结果
     */
    public static String sendGet(String url, String param) {
        String result = "";
        BufferedReader in = null;
        try {
        	param=param==null?"":param;
            String urlNameString = url + "?" + param;
            URL realUrl = new URL(urlNameString);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 建立实际的连接
            connection.connect();
            // 获取所有响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();
            // 遍历所有的响应头字段
            for (String key : map.keySet()) {
                System.out.println(key + "--->" + map.get(key));
            }
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream(),"UTF-8"));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送GET请求出现异常！" + e);
            e.printStackTrace();
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return result;
    }
    
//    public static String do_post(String postUrl,String postData) throws IOException {
//		String body = "";
////		String content = "您的验证码是：【" + codenum + "】。如需帮助请联系客服。";
////		content = java.net.URLEncoder.encode(content, "UTF-8");
////		String postUrl = "http://sms.106jiekou.com/utf8/sms.aspx";
////		String postData = "account=" + strS1[0] + "&password=" + strS1[1] + "" + "&mobile=" + mobile + "&content="
////				+ content + "";
//
//		// 发送POST请求
//		URL url = new URL(postUrl + "?" + postData);
//		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//		conn.setRequestMethod("POST");
//		conn.setRequestProperty("Content-Type", "application/x-java-serialized-object");
//		//conn.setRequestProperty("Connection", "Keep-Alive");
//		
//		conn.setDoOutput(true);
//		conn.setDoInput(true);
//		conn.setUseCaches(false);
//
//		conn.setRequestProperty("Content-Length", "" + postData.length());
//		OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
//		out.write(postData);
//		out.flush();
//	
//
//		// 获取响应状态
//		if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
//			System.out.println("connect failed!");
//			return "{resultMessage : \"验证失败！\"}";
//		}
//		// 获取响应内容体
//
//		BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
//		String line;
//		while ((line = in.readLine()) != null) {
//			//body += line;
//			body += new String(line.getBytes("ISO-8859-1"),"UTF-8");
//		}
//		in.close();
//		out.close();
//		if ("".equals(body)) {
//			body = "{resultMessage : \"验证失败！\"}";
//		} else if (body.equals("100")) {
////			body = String.valueOf(codenum);
//		} else if (body.equals("101")) {
//			body = "{resultMessage : \"验证失败！\"}";
//		} else {
//			//body = "验证失败！";
//		}
//		return body;
//	}
    
    public static String do_post(String postUrl,String postData) throws IOException {
    	
    	String body = "";
    	URL url = new URL(postUrl);    
        
    	URLConnection rulConnection = url.openConnection();// 此处的urlConnection对象实际上是根据URL的    
    	// 请求协议(此处是http)生成的URLConnection类    
    	// 的子类HttpURLConnection,故此处最好将其转化    
    	// 为HttpURLConnection类型的对象,以便用到    
    	// HttpURLConnection更多的API.如下:    
    	     
    	HttpURLConnection httpUrlConnection = (HttpURLConnection) rulConnection; 
    	
    	// 设定请求的方法为"POST"，默认是GET    
    	httpUrlConnection.setRequestMethod("POST");    
    	    
    	// 设置是否向httpUrlConnection输出，因为这个是post请求，参数要放在    
    	// http正文内，因此需要设为true, 默认情况下是false;    
    	httpUrlConnection.setDoOutput(true);    
    	     
    	// 设置是否从httpUrlConnection读入，默认情况下是true;    
    	httpUrlConnection.setDoInput(true);    
    	     
    	// Post 请求不能使用缓存    
    	httpUrlConnection.setUseCaches(false);    
    	     
    	// 设定传送的内容类型是可序列化的java对象    
    	// (如果不设此项,在传送序列化对象时,当WEB服务默认的不是这种类型时可能抛java.io.EOFException)    
    	httpUrlConnection.setRequestProperty("Content-type", "application/x-www-form-urlencoded");    
    	   
    	// 连接，从上述url.openConnection()至此的配置必须要在connect之前完成，    
    	httpUrlConnection.connect();    
    	
    	InputStream inStrm = httpUrlConnection.getInputStream(); 
    	BufferedReader in = new BufferedReader(new InputStreamReader(inStrm, "UTF-8"));
    	String line = "";
    	while ((line = in.readLine()) != null) {
    		System.out.println(line);
    		//System.out.println(new String(line.getBytes("ISO-8859-1"),"UTF-8"));
    		body += line;
		}
    	
    	
    	return body;
    }
    
    public static String post(String postUrl,List<NameValuePair> postData) throws IOException {
    	String result = "";
    	
    	CloseableHttpClient httpClient = HttpClients.custom().build();
    	HttpPost httpPost = new HttpPost(postUrl);
    	
//    	List<NameValuePair> params = new ArrayList<NameValuePair>();  
//      params.add(new BasicNameValuePair("serialNum", "I am Post String"));
    	if(postData != null && postData.size() > 0) {
    		httpPost.setEntity(new UrlEncodedFormEntity(postData,"UTF-8"));
    	}
        
        HttpResponse httpResponse = httpClient.execute(httpPost);  
        if(httpResponse.getStatusLine().getStatusCode() == 200)  
        {  
            HttpEntity httpEntity = httpResponse.getEntity();  
            result = EntityUtils.toString(httpEntity, "UTF-8");//取出应答字符串  
        }  
        
    	return result;
    }
    
    public static String test_post(String url, String requestMethod){
    	String result = "";
        InputStream is = null;
        try {
            String parameters = "";
            //请求方式是否为get
            boolean isGet = false;
            //请求方式是否为post
            boolean isPost = !isGet;
            /*if(isGet){
                url += "?"+ parameters;
            }*/

            URL u = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) u.openConnection();

            //请求的参数类型(使用restlet框架时，为了兼容框架，必须设置Content-Type为“”空)
            conn.setRequestProperty("Content-Type", "application/octet-stream");
            //conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            //设置连接超时时间
            conn.setConnectTimeout(50000);  
            //设置读取返回内容超时时间
            conn.setReadTimeout(50000);
            //设置向HttpURLConnection对象中输出，因为post方式将请求参数放在http正文内，因此需要设置为ture，默认false
            if(isPost){
                conn.setDoOutput(true);
            }
            //设置从HttpURLConnection对象读入，默认为true
            conn.setDoInput(true);
            //设置是否使用缓存，post方式不能使用缓存
            if(isPost){
                conn.setUseCaches(false);
            }
            //设置请求方式，默认为GET
            conn.setRequestMethod("POST");

            //post方式需要将传递的参数输出到conn对象中
            if(isPost){
                DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
                dos.writeBytes(parameters);
                dos.flush();
                dos.close();
            }

            //从HttpURLConnection对象中读取响应的消息
            //执行该语句时才正式发起请求
            is = conn.getInputStream();
            
            byte[] b = new byte[is.available()];
            is.read(b);
            result = new String(b,"UTF-8");
            System.out.println(result);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }
}
